﻿using Single.AppCore;
using Single.Sugar.Entity;
using Single.YitId;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Single.Sugar.Db
{
    public class DbContext
    {
        /// <summary>
        /// 数据库配置文件
        /// </summary>
        private static readonly List<ConnectionConfig> Options = GlobalApp.GetOptions<List<ConnectionConfig>>("SugarSettings:ConnectionStrings");

        /// <summary>
        /// 额外操作
        /// </summary>
        private static Action<SqlSugarClient> ConfigAction => (db) =>
        {
            db.CurrentConnectionConfig.ConfigureExternalServices = new ConfigureExternalServices
            {
                EntityService = (x, p) =>
                {
                    p.DbColumnName = UtilMethods.ToUnderLine(p.DbColumnName);
                },
                EntityNameService = (x, p) =>
                {
                    p.DbTableName = UtilMethods.ToUnderLine(p.DbTableName);
                }
            };

            db.Aop.DataExecuting = (obj, entityInfo) =>
            {
                if (entityInfo.OperationType == DataFilterType.InsertByObject)
                {
                    EntityAopInsertByObject(entityInfo.EntityValue, entityInfo);
                }
                else if (entityInfo.OperationType == DataFilterType.UpdateByObject)
                {
                    EntityAopUpdateByObject(entityInfo.EntityValue, entityInfo);
                }
            };
        };

        /// <summary>
        /// 数据 InsertByObject 用户信息填充
        /// </summary>
        /// <param name="entityInfo"></param>
        private static void EntityAopInsertByObject(object entity, DataFilterModel entityInfo)
        {
            if (entityInfo.EntityColumnInfo.IsPrimarykey && entity is BaseEntity) { (entity as BaseEntity)?.DataAopInsert(); }
        }

        /// <summary>
        /// 数据 UpdateByObject 用户信息填充
        /// </summary>
        /// <param name="entityInfo"></param>
        private static void EntityAopUpdateByObject(object entity, DataFilterModel entityInfo)
        {
            if (entityInfo.EntityColumnInfo.IsPrimarykey && entity is BaseEntity) { (entity as BaseEntity)?.DataAopUpdate(); }
        }

        /// <summary>
        /// 数据库实例
        /// </summary>
        internal static readonly DbScope DbScope = new DbScope(Options, ConfigAction);
    }
}